<template>
  <div class="water-quality-container">

    <el-row :gutter="20" class="header-row">
      <div class="popup-header">
        <div class="header-left">
          <h3>{{ featureData.name || '地图要素' }}</h3>
          <div class="tags-row">
            <el-tag
              v-if="stationInfo.controllevel !== undefined && stationInfo.controllevel !== null && stationInfo.controllevel !== ''"
              type="success" size="medium">{{ stationInfo.controllevel }}</el-tag>
            <el-tag
              v-if="stationInfo.ismanual !== undefined && stationInfo.ismanual !== null && stationInfo.ismanual !== ''"
              :type="stationInfo.ismanual === '1' ? 'success' : 'info'" size="medium">
              {{ stationInfo.ismanual === "1" ? '自动站' : '手动站' }}
            </el-tag>
            <el-tag
              v-if="stationInfo.rivername !== undefined && stationInfo.rivername !== null && stationInfo.rivername !== ''"
              type="primary" size="medium">{{ stationInfo.rivername }}</el-tag>
          </div>
        </div>
        <div class="header-right">
          <i class="el-icon-close close-btn" @click="closePopup"></i>
        </div>
      </div>
    </el-row>


    <!-- 水质状况区域 -->
    <el-card class="water-quality-card" shadow="never">
      <div slot="header" class="card-header">
        <div>水质状况</div>
        <div>{{ stationInfo.sampleTime }}</div>
      </div>


      <!-- 水质评价 -->
      <el-descriptions class="evaluation-descriptions">
        <el-descriptions-item label="水质评价">
          <el-badge class="evaluation-badge">
            <span class="deep-color">{{ overviewInfo.waterQuality }}</span>
          </el-badge>
        </el-descriptions-item>
        <el-descriptions-item label="水质指数">
          <span class="deep-color">{{ overviewInfo.segmentIndex }}</span>
        </el-descriptions-item>
      </el-descriptions>

      <!-- 监测指标 -->
      <div class="indicators-title">监测指标</div>
      <div class="indicators-container">
        <div v-for="(indicator, index) in indicators" :key="index" class="indicator-item"
          v-if="indicator.value !== undefined && indicator.value !== null">
          <div class="indicator-header">
            <span class="indicator-name">{{ indicator.name }}</span>
          </div>
          <div class="indicator-main">
            <span class="indicator-value">{{ indicator.value }}</span>
          </div>
        </div>
      </div>

      <!-- 超标提示 -->
      <el-alert v-if="exceedAlertTitle" class="exceed-alert" type="error" :closable="false">
        <template slot="title">
          <div class="exceed-alert-content">
            <span class="exceed-title">超标因子：</span>
            <span class="exceed-items">{{ exceedAlertTitle }}</span>
          </div>
        </template>
      </el-alert>

      <!-- 图表控制区域 -->
      <div class="chart-controls">
        <div class="period-control">
          <el-radio-group v-model="timePeriod" @change="handlePeriodChange" size="small">
            <el-radio-button label="month"><i class="fa fa-calendar"></i> 月</el-radio-button>
            <el-radio-button label="year"><i class="fa fa-calendar"></i> 年</el-radio-button>
          </el-radio-group>
        </div>
        <div class="time-range-control">
          <el-date-picker v-if="timePeriod === 'month'" v-model="dateRange" :type="datePickerType" range-separator="至"
            :start-placeholder="datePickerStartPlaceholder" :end-placeholder="datePickerEndPlaceholder" size="small">
          </el-date-picker>
          <!-- 当timePeriod为year时，使用两个独立的year选择器 -->
          <div v-if="timePeriod === 'year'" class="year-range-picker">
            <el-date-picker v-model="yearRangeStart" type="year" :placeholder="datePickerStartPlaceholder" size="small">
            </el-date-picker>
            <span class="range-separator">至</span>
            <el-date-picker v-model="yearRangeEnd" type="year" :placeholder="datePickerEndPlaceholder" size="small">
            </el-date-picker>
          </div>

          <el-button type="primary" @click="handleQuery" class="query-btn" size="small">
            <i class="fa fa-search"></i> 查询
          </el-button>
        </div>
      </div>
      <!-- 图表容器 -->
      <div class="chart-container">
        <el-card shadow="never">
          <div ref="chart" class="echart-container"></div>
        </el-card>
      </div>
    </el-card>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { getinfo, getAutoStationInfo, getManuaStationMonthTrend, getManuaStationYearTrend } from '@/views/biz/api/shougongduanmian'


export default {
  name: 'shougongduanmianPopup',
  data() {
    return {
      controlLevel: '县控',
      stationInfo: {},
      exceedAlertTitle: '',
      // 时间周期：hour, day, month ,year
      timePeriod: 'month',
      // 日期范围
      dateRange: [
      ],
      yearRangeStart: null,
      yearRangeEnd: null,

      // 水质指标数据
      overviewInfo: [],
      indicators: [],
      targetQuality: 2,
      times: ["2025-08-10 00:00",
        "2025-08-10 01:00",
        "2025-08-10 02:00",
        "2025-08-10 03:00",
        "2025-08-10 04:00",
        "2025-08-10 05:00",
        "2025-08-10 06:00",
        "2025-08-10 07:00",
        "2025-08-10 08:00",
        "2025-08-10 09:00",
        "2025-08-10 10:00"],
      qualityData: [2, 2, 2, 2, 2, 0, 2, 3, 3, 3, 3],
      monitoringData: {},
      // 图表实例
      chart: null,
      levelMap: {
        "劣Ⅴ类": 6,
        "Ⅴ类": 5,
        "Ⅳ类": 4,
        "Ⅲ类": 3,
        "Ⅱ类": 2,
        "Ⅰ类": 1,
        "无类别": 0
      }
    }
  },
  props: {
    featureId: {
      type: String,
      default: ''
    },
    featureData: {
      type: Object,
      default: () => ({})
    }
  },
  computed: {
    datePickerType() {
      switch (this.timePeriod) {
        case 'hour':
          return 'datetimerange';
        case 'day':
          return 'daterange';
        case 'month':
          return 'monthrange';
        case 'year':
          return 'year';
        default:
          return 'datetimerange';
      }
    },
    datePickerStartPlaceholder() {
      switch (this.timePeriod) {
        case 'hour':
          return '开始时间';
        case 'day':
          return '开始日期';
        case 'month':
          return '开始月份';
        case 'year':
          return '开始年份';
        default:
          return '开始时间';
      }
    },
    datePickerEndPlaceholder() {
      switch (this.timePeriod) {
        case 'hour':
          return '结束时间';
        case 'day':
          return '结束日期';
        case 'month':
          return '结束月份';
        case 'year':
          return '结束年份';
        default:
          return '结束时间';
      }
    },
    targetQualityText() {
      const qualityMap = {
        6: "劣Ⅴ类",
        5: "Ⅴ类",
        4: "Ⅳ类",
        3: "Ⅲ类",
        2: "Ⅱ类",
        1: "Ⅰ类"
      };
      return qualityMap[this.targetQuality] || '未知';
    }
  },
  watch: {
    featureId: {
      handler(newVal, oldVal) {
        if (newVal) {
          //console.log('featureId', newVal)
        }
      },
      immediate: true
    },
  },
  mounted() {

    this.initDateRange();
    this.getbaseinfo()
    this.getStationInfo();
    this.getMonitoringData();
  },
  beforeDestroy() {
    // 销毁图表实例，释放资源
    if (this.chart) {
      this.chart.dispose()
    }
    // 移除事件监听
    window.removeEventListener('resize', this.handleResize)
  },
  methods: {
    closePopup() {
      this.$emit('close');
    },
    formatHour(date) {
      if (!date) return '';
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    formatDate(date) {
      if (!date) return '';
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    formatMonth(date) {
      if (!date) return '';
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      return `${year}-${month}`;
    },
    formatYear(date) {
      if (!date) return '';
      const year = date.getFullYear();

      return `${year}`;
    },

    initDateRange() {
      let end = new Date();
      let start = new Date();
      start.setMinutes(0, 0, 0);

      switch (this.timePeriod) {
        case 'hour':
          end.setMinutes(0, 0, 0); // 将分钟、秒、毫秒设置为0，实现小时取整
          start.setTime(start.getTime() - 3600 * 1000 * 24); // 前24小时
          break;
        case 'day':
          end.setHours(0, 0, 0, 0); // 设置为当天0点
          start.setHours(0, 0, 0, 0);
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 7); // 前24天
          break;
        case 'month':
          end.setDate(1); // 设置为当月1号
          end.setHours(0, 0, 0, 0);
          start.setMonth(start.getMonth() - 12); // 前24个月
          break;
        case 'year':
          start.setFullYear(start.getFullYear() - 10);
          this.yearRangeStart = start
          this.yearRangeEnd = end
          break;
      }
      this.dateRange = [start, end];
    },

    getbaseinfo() {
      getinfo({ id: this.featureId }).then(res => {
        this.stationInfo = res.data;
        // 优化targetLevelName为NULL时的处理
        if (res.data.targetlevelname && this.levelMap[res.data.targetlevelname] !== undefined) {
          this.targetQuality = this.levelMap[res.data.targetlevelname];
        } else {

          this.targetQuality = 2; // 默认为Ⅱ类
        }
      })
    },
    getStationInfo() {
      getAutoStationInfo({ id: this.featureId }).then(res => {
        this.overviewInfo = res.data;
        this.indicators = res.data.itemDataList.map(item => ({
          ...item,
          value: item.value !== undefined && item.value !== null && item.value !== '' ? item.value : 0
        }));
        let overstandardList = res.data.overstandardList;
        this.exceedAlertTitle = overstandardList.map(item => `${item.name}(${item.value})`).join(',');
      })
    },
    getMonitoringData() {
      let apiFunction;
      let startTime;
      let endTime;

      if (this.timePeriod === 'year') {
        apiFunction = getManuaStationYearTrend;
        startTime = this.formatYear(this.yearRangeStart);
        endTime = this.formatYear(this.yearRangeEnd);
      } else if (this.timePeriod === 'month') {
        apiFunction = getManuaStationMonthTrend;
        startTime = this.formatMonth(this.dateRange[0]);
        endTime = this.formatMonth(this.dateRange[1]);
      } else {
        console.warn('未知的时间段类型:', this.timePeriod);
        return;
      }

      apiFunction({
        id: this.featureId,
        startTime: startTime,
        endTime: endTime
      }).then(res => {
        this.monitoringData = this.convertData(res.data);
        this.times = this.monitoringData.dateList;
        this.qualityData = this.monitoringData.value;
        this.renderChart();
      }).catch(error => {
        console.error('获取监测数据失败:', error);
      });
    },

    // 转换函数：生成value数组
    convertData(data) {
      // 根据level数组生成对应的数值数组
      const value = data.level.map(level => this.levelMap[level]);

      // 返回包含value的新对象
      return {
        value,
        ...data  // 保留原始的level、levelList和dateList
      };
    },



    // 处理时间周期变化
    handlePeriodChange() {
      this.initDateRange();
      this.getMonitoringData();
    },

    // 处理日期范围变化
    handleDateChange() {
      this.getMonitoringData();
    },

    // 处理查询
    handleQuery() {
      if (this.timePeriod === 'month') {
        if (!this.dateRange || this.dateRange.length !== 2) {
          this.$message.error('请选择开始时间和结束时间')
          return
        }

        if (this.dateRange[0] > this.dateRange[1]) {
          this.$message.error('开始时间不能晚于结束时间')
          return
        }
      }

      if (this.timePeriod === 'year') {
        if (!this.yearRangeEnd || !this.yearRangeStart) {
          this.$message.error('请选择开始时间和结束时间')
          return
        }

        if (this.yearRangeStart > this.yearRangeEnd) {
          this.$message.error('开始时间不能晚于结束时间')
          return
        }
      }


      this.getMonitoringData();
    },


    getOption() {
      // ECharts配置项
      const option = {
        title: {
          text: '水质趋势图',
          left: 'center',
          textStyle: {
            fontSize: 16,
            fontWeight: 'bold'
          },
          padding: [0, 0, 20, 0]
        },
        tooltip: {
          trigger: 'axis',
          backgroundColor: 'rgba(255, 255, 255, 0.9)',
          borderColor: '#ddd',
          borderWidth: 1,
          textStyle: {
            color: '#333'
          },
          formatter: params => {
            let result = `<div style="font-weight:bold">时间: ${params[0].name}</div>`
            params.forEach(item => {
              if (item.seriesType === 'line') {
                result += `<div style="display:flex;align-items:center;margin-top:5px">
                  <span style="display:inline-block;width:10px;height:10px;background-color:${item.color};margin-right:5px;border-radius:50%"></span>
                  ${item.seriesName}: ${item.value}
                </div>`
              }
            })
            return result
          }
        },
        legend: {
          show: true,
          top: 'bottom',
          left: 'center'
        },
        grid: {
          left: '3%',
          right: '7%',
          bottom: '20%',
          top: '15%',
          containLabel: true
        },
        toolbox: {
          feature: {
            saveAsImage: {
              title: '保存图片'
            },
            dataZoom: {
              title: {
                zoom: '区域缩放',
                back: '缩放还原'
              }
            },
            restore: {
              title: '还原'
            }
          }
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: this.times,
          // axisLabel: {
          //   interval: 'auto',
          //   maxInterval: 10
          // },
          name: '监测时间',
          nameLocation: 'middle',
          nameGap: 30
        },
        yAxis: [
          {
            type: 'value',
            name: '水质',
            nameLocation: 'middle',
            nameGap: 50,
            min: 0,
            max: 6,
            splitLine: {
              lineStyle: {
                color: 'rgba(0, 0, 0, 0.05)'
              }
            }
          }
        ],
        series: [
          {
            name: '水质',
            type: 'line',
            data: this.qualityData,
            symbol: 'circle',
            symbolSize: 6,
            emphasis: {
              symbolSize: 8
            },
            lineStyle: {
              width: 3,
              color: '#4bc0c0'
            },
            itemStyle: {
              color: '#4bc0c0'
            },
            smooth: true,
            markLine: {
              data: [
                {
                  type: 'value',
                  name: '目标水质',
                  yAxis: this.targetQuality,
                  lineStyle: {
                    color: '#dc3545',
                    type: 'dashed',
                    width: 2
                  },
                  label: {
                    show: true,
                    position: 'end',
                    color: '#dc3545'
                  }
                },

              ]
            }
          }
        ],
        dataZoom: [
          {
            type: 'inside',
            xAxisIndex: 0,
            start: 0,
            end: 100
          },
          {
            show: !this.isMobile, // 移动端隐藏滑动条
            type: 'slider',
            xAxisIndex: 0,
            start: 0,
            end: 100,
            bottom: 50
          }
        ],
        animation: true,
        animationDuration: 1000,
        animationEasing: 'cubicOut'
      }
      this.chart.setOption(option, true)

    },
    // 渲染图表
    renderChart() {
      if (!this.chart) {
        this.chart = echarts.init(this.$refs.chart)
        this.getOption()
      }
      else {
        this.getOption()
      }
    },

    // 处理窗口大小变化
    handleResize() {
      if (this.chart) {
        this.chart.resize()
      }
    }
  }
}
</script>

<style scoped>
.water-quality-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 15px;
  background-color: #f9fafb;
}


.header-row {
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.popup-header {
  padding: 12px 16px;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  flex-shrink: 0;
}

.header-left {
  display: flex;
}

.tags-row {
  margin-left: 10px;
}

.header-left h3 {
  margin: 0;
  font-size: 20px;
  color: #303133;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: calc(100% - 30px);
  font-weight: bold;

}

.header-right {
  display: flex;
  align-items: flex-start;
  margin-left: 10px;
}

.close-btn {
  cursor: pointer;
  font-size: 18px;
  color: #909399;
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.close-btn:hover {
  color: #409EFF;
}




.water-quality-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  /* 左右两端对齐 */
  align-items: center;
  /* 垂直居中对齐（可选） */
  width: 100%;
  /* 确保容器占满可用宽度 */
}

/* 字体加粗 */
.card-header div {
  font-weight: bold;
}

.evaluation-descriptions {
  margin-bottom: 20px;
  background-color: #f8fafc;
  padding: 10px;
}

.deep-color {
  color: #333 !important;
  font-weight: 500;
}

/* 加深 label 文字 */
.evaluation-descriptions ::v-deep .el-descriptions__label {
  color: #333 !important;
}

.indicators-title {
  font-weight: bold;
  margin-bottom: 10px;
  color: #333;
}

.indicators-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
  gap: 15px;
  margin-bottom: 20px;
}

.indicator-item {
  border-radius: 6px;
  padding: 5px;
  background-color: #fff;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  border: 1px solid #eee;
}

.indicator-item:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.indicator-item.exceed-limit {
  border-left: 4px solid #f56c6c;
}

.indicator-item.normal {
  border-left: 4px solid #409eff;
}

.indicator-item.good {
  border-left: 4px solid #67c23a;
}

.indicator-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.indicator-name {
  font-weight: 500;
  color: #333;
  font-size: 14px;
}

.indicator-status {
  font-size: 16px;
}

.indicator-item.exceed-limit .indicator-status {
  color: #f56c6c;
}

.indicator-item.normal .indicator-status {
  color: #409eff;
}

.indicator-item.good .indicator-status {
  color: #67c23a;
}

.indicator-main {
  margin-bottom: 8px;
}

.indicator-value {
  font-weight: bold;
  font-size: 18px;
  color: #333;
  margin-right: 5px;
}

.indicator-range {
  font-size: 12px;
  color: #999;
}

.indicator-footer {
  font-size: 12px;
}

.indicator-desc {
  color: #666;
}

.exceed-alert {
  margin-bottom: 20px;
  border-radius: 4px;
}

.chart-controls {
  margin-bottom: 20px;
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.period-control {
  width: 100%;
}

.time-range-control {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
  align-items: center;
  width: 100%;
}

.query-btn {
  white-space: nowrap;
}

.echart-container {
  width: 600px;
  height: 300px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .water-quality-container {
    padding: 10px;
  }

  .chart-controls {
    flex-direction: column;
    align-items: stretch;
  }

  .time-range-control {
    width: 100%;
  }

  .echart-container {
    height: 300px;
  }


  .indicators-container {
    grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
  }

  .indicator-item {
    padding: 12px;
  }

  .indicator-value {
    font-size: 16px;
  }
}
</style>